package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("ProductcodeService")
@Transactional

public class ProductcodeServiceImpl extends CmiEmaService implements ProductcodeService {
	public ProductcodeServiceImpl() {
	}

	@Transactional
	public Productcode saveProductcode(Productcode productcode) {
		Set<Food> existingFoodsForProductcode = new HashSet<Food>();

		Set<Food> selectedFoodsForProductcode = productcode.getFoodsForProductcode();

		if (productcode.getId() == null) {

			Productcode existingProductcode = productcodeDAO.findProductcodeByPhysicalPrimaryKey(productcode.getName());

			if (isEquals(productcode, existingProductcode)) {
				return existingProductcode;
			}

			productcode = productcodeDAO.store(productcode);
			productcodeDAO.flush();

			for (Food relatedFood : selectedFoodsForProductcode) {
				relatedFood.setProductcode(productcode);
				foodDAO.store(relatedFood);
			}
		} else {
			Productcode existingProductcode = productcodeDAO.findProductcodeByPrimaryKey(productcode.getId());

			existingFoodsForProductcode = existingProductcode.getFoodsForProductcode();

			Set<Food> prepareDeleteFoodsForProductcode = new HashSet<Food>();
			Set<Food> prepareAddFoodsForProductcode = new HashSet<Food>();

			prepareDeleteFoodsForProductcode.addAll(selectedFoodsForProductcode);
			prepareDeleteFoodsForProductcode.addAll(existingFoodsForProductcode);

			prepareAddFoodsForProductcode.addAll(selectedFoodsForProductcode);
			prepareAddFoodsForProductcode.addAll(existingFoodsForProductcode);

			prepareDeleteFoodsForProductcode.removeAll(selectedFoodsForProductcode);
			prepareAddFoodsForProductcode.removeAll(existingFoodsForProductcode);

			for (Food relatedFood : prepareAddFoodsForProductcode) {
				relatedFood.setProductcode(productcode);
				foodDAO.store(relatedFood);
			}

			for (Food relatedFood : prepareDeleteFoodsForProductcode) {
				relatedFood.setProductcode(null);
				foodDAO.store(relatedFood);
			}
			productcode = productcodeDAO.store(productcode);
			productcodeDAO.flush();
		}

		foodDAO.flush();
		return productcode;
	}

	public void deleteProductcode(Productcode productcode) {
		productcodeDAO.remove(productcode);
		productcodeDAO.flush();
	}

	@Transactional
	public void deleteProductcodes(Set<Integer> deleteProductcodesId) {
		Query query = productcodeDAO.createNamedQuery("deleteProductcodesById", -1, -1);
		query.setParameter(1, deleteProductcodesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Productcode> loadProductcodes() {
		return productcodeDAO.findAllProductcodes();

	}

	@Transactional
	public Set<Productcode> loadReferenceProductcodes(Set<Productcode> productcodes) {
		Iterator<Productcode> productcodesIterator = productcodes.iterator();
		Set<Productcode> referencedProductcodes = new HashSet<>();
		while (productcodesIterator.hasNext()) {
			Productcode currentProductcode = productcodesIterator.next();

			if (!currentProductcode.getFoodsForProductcode().isEmpty()) {
				referencedProductcodes.add(currentProductcode);
				continue;
			}
		}
		return referencedProductcodes;
	}

	public Set<Productcode> loadProductcodesByIdSet(Set<Integer> productcodeIdSet) {

		Iterator<Integer> productcodeIdIterator = productcodeIdSet.iterator();
		Set<Productcode> productcodeSet = new HashSet<>();
		while (productcodeIdIterator.hasNext()) {
			Integer id = productcodeIdIterator.next();
			Productcode currentProductcode = productcodeDAO.findProductcodeById(id);
			productcodeSet.add(currentProductcode);
		}
		return productcodeSet;
	}

	@Transactional
	public List<Productcode> findAllProductcodes(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Productcode>(productcodeDAO.findAllProductcodes(startResult, maxRows));
	}

	@Transactional
	public Productcode findProductcodeByPrimaryKey(Integer id) {
		return productcodeDAO.findProductcodeByPrimaryKey(id);
	}

	@Transactional
	public Integer countProductcodes() {
		return ((Long) productcodeDAO.createQuerySingleResult("select count(o) from Productcode o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countProductcodes(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Productcode.class);
		return ((Long) productcodeDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countProductcodesByName(String queryName) {
		Query query = productcodeDAO.createNamedQuery("countProductcodesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countProductcodesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Productcode.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadProductcodeObjectReferencedSet(Productcode productcode) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> foodsIds = new HashSet<Integer>();
		for (Food obj : productcode.getFoodsForProductcode()) {

			foodsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("foodsIds", foodsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadProductcodeClassReferencedSet(Productcode productcode) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());

		return classReferencedSetMap;
	}

	public boolean isEquals(Productcode productcode, Object obj) {
		if (obj == productcode)
			return true;
		if (!(obj instanceof Productcode))
			return false;
		Productcode comparedProductcode = (Productcode) obj;
		if (!CheckPropertyEqual(productcode.getName(), comparedProductcode.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

